package com.framework.spring.lifeCycle.lc.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import java.lang.reflect.Method;

@Slf4j(topic = "e")
//@Component
public class JDKProxyBeanPostProcessor implements BeanPostProcessor {
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if ("d".equals(beanName)) {
			ClassLoader classLoader = this.getClass().getClassLoader();
			Class<?>[] interfaces = bean.getClass().getInterfaces();
			return Proxy.newProxyInstance(classLoader, interfaces, new MyInvocatinHandler(bean));
		}
		return bean;
	}

	class MyInvocatinHandler implements InvocationHandler{
		Object target;

		public MyInvocatinHandler(Object target) {
			this.target = target;
		}

		@Override
		public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
			log.info("invoke before");
			Object invoke = method.invoke(target, objects);
			log.info("invoke after");
			return invoke;
		}
	}
}
